package com.heima.gateway.filter;

import com.heima.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Service
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {
    /**
     * 设置过滤器
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求和响应
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //判断是否要鉴权,包含login则放行
        String path = request.getURI().getPath();
        if(path.contains("/login")){
            //包含login则放行
            return chain.filter(exchange);
        }
        //判断请求头是否有token
        String token = request.getHeaders().getFirst("token");
        if(StringUtils.isEmpty(token)){
            //为空则返回401提示
             response.setStatusCode(HttpStatus.UNAUTHORIZED);
             return response.setComplete();
        }
        //有token则判断token是否有效
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            int result = AppJwtUtil.verifyToken(claimsBody);
            System.out.println(result);
            // 0,-1 有效则放行
            if(result==0 || result==-1){
                //有效则解析token得userId
                Object userId = claimsBody.get("userId");
                //放入到请求头中给后端
                request.mutate().header("userId",userId.toString());
                return chain.filter(exchange);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        // 1,2 过期则提示401
       response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    /**
     * 过滤器顺序
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
